import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'
import store from '@/store'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/index'
  },
  {
    path: '/index',
    name: 'index',
    component: Home,
    meta: {
      requiresAuth: true
    }
  },
  {
    path: '/about',
    name: 'about',
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () => import(/* webpackChunkName: "about" */ '../views/About.vue'),
    meta: {
      requiresAuth: false
    }
  },
  {
    path:'/login',
    name:'login',
    component: () => import( '../views/Login.vue'),
    meta: {
      requiresAuth: false
    }
  },
  {
    path:'/register',
    name:'register',
    component: () => import( '../views/Register.vue'),
        meta: {
      requiresAuth: false
    }

  },
  {
    path:'/create',
    name:'create',
    component: () => import( '../views/create.vue'),
        meta: {
      requiresAuth: false
    }

  }
]

const router = new VueRouter({
  mode: 'history',
  routes
})

// 注册全局钩子用来拦截导航
router.beforeEach((to, from, next) => {
    let token = store.getters.token
  if (to.meta.requiresAuth) {
    if (token) {
      //store.dispatch('getUser')
      next()
    } else {
      store.dispatch('user/loginOut')
      next({
        path: '/login',
        query: { redirect: to.fullPath }
      })
    }
  } else {
    next()
  }
})
export default router
